<?

# 
# Copyright (c) 2002-2007 Eric Wallengren
# This file is part of the Continuous Automated Build and Integration 
# Environment (CABIE)
# 
# CABIE is distributed under the terms of the GNU General Public
# License version 2 or any later version.  See the file COPYING for copying 
# permission or http://www.gnu.org. 
#                                                                            
# THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED OR  
# IMPLIED, without even the implied warranty of MERCHANTABILITY or FITNESS 
# FOR A PARTICULAR PURPOSE.  ANY USE IS AT YOUR OWN RISK. 
#                                                                            
# Permission to modify the code and to distribute modified code is granted, 
# provided the above notices are retained, and a notice that the code was 
# modified is included with the above copyright notice. 
# 

    include_once("jobinfo.php");
    include_once("Sajax.php");
    include_once("dbdefs.php");
    include_once("cmddefs.php");
    include_once("menuperms.php");

    function _getactiveservers($SQL, $type) {
    
        if ($type) {
            $sqlarray = $SQL->sql_query("select server from configuration ".
                                        "where state='0' order by server", 
                                        ";");
        } else {
            $sqlarray = $SQL->sql_query("select server from buildservers ".
                                        "where status='1'", ";");
        }

        return $sqlarray;

    }

    function _serverup($SQL, $servername) {

        $sqlarray = $SQL->sql_query("select server from buildservers where ".
                                    "status='1' and server=\"$servername\"", 
                                    ";");

        return count($sqlarray);

    }

    function _returnlevel($SQL, $username) {

        $sqlarray = $SQL->sql_query("select realmid from users where ".
                                    "username='$username'", 
                                    ";");
        $userlevel = $sqlarray[0];

        return $userlevel;

    }

    function _verifylevel($SQL, $username, $level) {

        $sqlarray = $SQL->sql_query("select realmid from users where ".
                                    "username='$username'", 
                                    ";");
        $userlevel = $sqlarray[0];

        if ($userlevel >= $level) {
            return 1;
        } else {
            return 0;
        }

    }
    
    function _debug($message) {

        echo "<pre>$message</pre>\n";

    }

    function _randomimage($path) {

        srand(time());
        $filearray = array();

        $a = 1;

        if (is_dir($path)) {
            if($dh = opendir($path)) {
                while(($file = readdir($dh)) !== FALSE) {
                    if ($file !== "."  && $file !== "..") {
                        $filearray[$a] = $file;
                        $a++;
                    }
                }
                closedir($dh);
            }
        }
                
        $random = (rand()%$a-1);

        return($filearray[$random]);

    }

    function _isEqual($val1, $val2) {

        if (!strcmp($val1, $val2) != 0) {
            $ret = 1;
        } else {
            $ret = 0;
        }

        return $ret;

    }

    function _servermenu($SQL, $buildserver) {

        if (isset($_REQUEST['recs'])) {
            $toshow = $_REQUEST['recs'];
        } else {
            $toshow = 10;
        }

        $PERMS = new menuperms();
        $PERMS->__construct('bla');

        $isie = _isie();

        if ($isie) {
            $ext = 'gif';
        } else {
            $ext = 'png';
        }

        $user = $_SESSION['PHP_AUTH_USER'];

        $servermenu = array(

            "home"        => array(
                "name"    => "home",
                "parent"  => "/cabie.php",
                "link"    => "?server=$buildserver&action=view",
                "tooltip" => "server home",
                "icon"    => "application_home.$ext"
            ),
            /*
            "expand"      => array(
                "name"    => "expand",
                "parent"  => "\"#\" ",
                "link"    => "onclick=\"return toggleAll('expand')\"",
                "tooltip" => "expand all jobs",
                "icon"    => "arrow_down.$ext"
            ),
            "collapse"    => array(
                "name"    => "collapse",
                "parent"  => "\"#\" ",
                "link"    => "onclick=\"return toggleAll('collapse')\"",
                "tooltip" => "collapse all jobs",
                "icon"    => "arrow_up.$ext"
            ),
            */
            "sysinfo"     => array(
                "name"    => "sysinfo",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=sysinfo&server=$buildserver",
                "tooltip" => "system information",
                "icon"    => "information.$ext"
            ),
            "processes"   => array(
                "name"    => "processes",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=ps&server=$buildserver",
                "tooltip" => "running processes",
                "icon"    => "table.$ext"
            ),
            "teststatus"  => array(
                "name"    => "teststatus",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=teststatus&server=$buildserver&jobname=".
                             "all",
                "tooltip" => "all tests executed",
                "icon"    => "cog.$ext"
            ),
            "set"         => array(
                "name"    => "set",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=set&server=$buildserver&jobname=all",
                "tooltip" => "$buildserver environment",
                "icon"    => "building.$ext"
            ),
            "removed"     => array(
                "name"    => "removed",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=removed&server=$buildserver",
                "tooltip" => "retired jobs",
                "icon"    => "report_delete.$ext"
            ),
            "servers"     => array(
                "name"    => "servers",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=servers&server=$buildserver",
                "tooltip" => "other servers",
                "icon"    => "server_database.$ext"
            ),
            "dumpconfig"  => array(
                "name"    => "dumpconfig",
                "parent"  => "/adminbroker.php",
                "link"    => "?cmd=dumpconfig&server=$buildserver&access=".
                             "login",
                "tooltip" => "$buildserver configuration",
                "icon"    => "application_view_list.$ext"
            ),
            "shutdown"    => array(
                "name"    => "shutdown",
                "parent"  => "/adminbroker.php",
                "link"    => "?cmd=shutdown&server=$buildserver&sleep=1&recs".
                             "=$toshow".
                             "access=login",
                "tooltip" => "stop buildserver",
                "icon"    => "stop.$ext"
            ),
            "users"  => array(
                "name"    => "users",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=viewusers&server=$buildserver",
                "tooltip" => "view users",
                "icon"    => "group.$ext"
            ),
            "login"  => array(
                "name"    => "login",
                "parent"  => "/adminbroker.php",
                "link"    => "?server=$buildserver&access=login&sleep=1&recs".
                             "=$toshow",
                "tooltip" => "login",
                "icon"    => "status_offline.$ext"
            ),
            "logout"  => array(
                "name"    => "logout",
                "parent"  => "/adminbroker.php",
                "link"    => "?access=logout&sleep=1",
                "tooltip" => "logout $user",
                "icon"    => "status_online.$ext"
            ),

        );

        echo "<tr>\n".
             "    <td class=serveract colspan=8>$buildserver&nbsp;\n";

        foreach ($servermenu as $command) {

            $level    = $PERMS->_servermenu($command['name']);

            switch($command['name']) {
             
                case 'logout':
                    if (isset($user)) {
                        _genlink($command);
                    }
                    break;
                case 'login':
                    if (!isset($user)) {
                        _genlink($command);
                    }
                    break;
                default:
                    $ok = _verifylevel($SQL, $user, $level);
                    if ($ok) {
                        _genlink($command);
                    }
                    break;
            }

        }

        echo "    </td>\n".
             "</tr>\n";

    }

    function _genlink($command) {

         echo "\t<a href=".$command['parent'].$command['link']." ".
              "onmouseover=\"Tip('".$command['tooltip']."')\">".
              "<img src=/cabieicons/".$command['icon']."></a>&nbsp;\n";
    }

    #
    # This is the menu for each job, displayed to the left of the jobname
    #
    function _jobmenu($SQL, $buildserver, $rec, $runstatus, $colspan) {

        if (isset($_REQUEST['recs'])) {
            $toshow = $_REQUEST['recs'];
        } else {
            $toshow = 10;
        }

        #
        # Target id for ajax operations
        #
        $id = $rec."_id";

        #
        # Each menu control has a set access level defined in menuperms.
        #
        $PERMS = new menuperms();
        $PERMS->__construct();

        $recs = $_REQUEST['recs'];

        #
        # If we're IE we'll load transparent gifs
        #
        $isie = _isie();

        if ($isie) {
            $ext = 'gif';
        } else {
            $ext = 'png';
        }

        #
        # See if there is a user loggen into this session
        #
        $user = $_SESSION['PHP_AUTH_USER'];

        #
        # Define each menu entry here:
        #
        # name: uniques identifier for the menu item
        # parent: the parent to be called with a set of args
        # link: the args supplied to the parent
        # tooltip: message displayed when mousing over selection
        # icon: the icon displayed for the menu item
        # func: an internal function to be used which will be used to 
        #       define all of the above
        # args: arguments to be sent to what's defined as func
        #
        $jobmenu = array(

            "expand"      => array(
                "name"    => "expand",
                "parent"  => "\"#\" ",
                "link"    => "onclick=\"do_expandJobInfo('$id', '0', 1)\"",
                "tooltip" => "collapse/expand job $rec",
                "icon"    => "application_side_expand.$ext"
            ),
            "killjob"    => array(
                "name"    => "killjob",
                "parent"  => "/adminbroker.php",
                "link"    => "?cmd=killjob&server=$buildserver&jobname=$rec".
                             "&sleep=1&access=login",
                "tooltip" => "kill running job $rec",
                "icon"    => "stop.$ext",
            ),
            "enable"      => array(
                "name"    => "enable",
                "func"    => "_jobstatus",
                "args"    => "enable,$buildserver,$rec",
            ),
            "editor"      => array(
                "name"    => "editor",
                "parent"  => "/editor.php",
                "link"    => "?server=$buildserver&name=$rec&action=edit".
                             "&table=configuration&user=1&access=login",
                "tooltip" => "edit $rec",
                "icon"    => "table_edit.$ext",
            ),
            "removejob"   => array(
                "name"    => "removejob",
                "parent"  => "/adminbroker.php",
                "link"    => "?cmd=removejob&server=$buildserver&jobname=$rec".
                             "&sleep=1&access=login",
                "tooltip" => "retire $rec job",
                "icon"    => "delete.$ext",
            ),
            "teststatus"  => array(
                "name"    => "teststatus",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=teststatus&server=$buildserver&jobname=".
                             "$rec&user=1",
                "tooltip" => "all tests executed for $rec",
                "icon"    => "cog.$ext"
            ),
            "debug"       => array(
                "name"    => "debug",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=debuglog&server=$buildserver&jobname=$rec".
                             "&user=1",
                "tooltip" => "last debuglog for $rec",
                "icon"    => "bug.$ext"
            ),
            "instruct"    => array(
                "name"    => "instruct",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=instructions&server=$buildserver&jobname=".
                             "$rec&user=1",
                "tooltip" => "$rec build instructions",
                "icon"    => "information.$ext"
            ),
            "lastchange"  => array(
                "name"    => "lastchange",
                "parent"  => "/userbroker.php",
                "link"    => "?cmd=lastchange&server=$buildserver&jobname=".
                             "$rec&user=1",
                "tooltip" => "last changes for $rec",
                "icon"    => "zoom.$ext"
            ),
            "pending"     => array(
                "name"    => "pending",
                "func"    => "_pending",
                "args"    => "nextjob,$buildserver,$rec",
            ),

        );

        echo "<tr>\n".
             "    <td class=\"".$runstatus['class']."\" colspan=$colspan>\n";

        foreach ($jobmenu as $command) {

            $level    = $PERMS->_jobmenu($command['name']);

            $ok = _verifylevel($SQL, $user, $level);

            if (!isset($command['func'])) {
                if ($ok) {
                    _genlink($command);
                }
            } else {
                if ($ok) {
                    $func    = $command['func'];
                    $args    = explode(",", $command['args']);
                    $cmdret  = $func($SQL, $args);
                    foreach ($cmdret as $runcmd) {
                        _genlink($runcmd);
                    }
                }
            }
        }

        echo "$rec&nbsp;".$runstatus['message']."\n".
             "    </td>\n".
             "</tr>\n";

    }

    #
    # Internal function called from _jobmenu.  Uses the same parameters 
    # as jobmenu, but looks for pending changes related to a particular
    # job.
    #
    function _pending($sql, $args) {

        #
        # Gather up all args
        #
        $cmd    = array_shift($args);
        $server = array_shift($args);
        $job    = array_shift($args);

        #
        # Figure out which image to display
        #
        $isie = _isie();

        if ($isie) {
            $ext = 'gif';
        } else {
            $ext = 'png';
        }

        #
        # QUery the database for any pending changes
        #
        $sqlarray = $sql->sql_query("select title from pending where ".
                                    "server=\"$server\" and title=\"$job\""
                                    , ";");

        #
        # Count up all records found
        #
        $recs = count($sqlarray);

        #
        # If there are any records, put together an array useable by 
        # the method in _jobmenu for displaying a menu item.
        #
        if ($recs) {

            $command   = array(
                
                "nextjob" => array(
                    "parent"  => "/userbroker.php",
                    "link"    => "?cmd=$cmd&server=$server&jobname=".
                                 "$job&user=1",
                    "tooltip" => "pending changes for $job",
                    "icon"    => "exclamation.$ext"
                )
    
            );

        } else {

            #
            # No records found, return empty array
            #
            $command = array();

        }

        return $command;

    }

    #
    # Internal function called from _jobmenu.  Uses the same parameters 
    # as jobmenu, but checks to see if a job is locked.
    #
    function _jobstatus($sql, $args) {

        #
        # Gather up all args
        #
        $cmd    = array_shift($args);
        $server = array_shift($args);
        $job    = array_shift($args);

        #
        # Figure out which image to display
        #
        $isie = _isie();

        if ($isie) {
            $ext = 'gif';
        } else {
            $ext = 'png';
        }

        #
        # Grab message from the semaphores table based upon the jobname and
        # build server.
        #
        $sqlarray = $sql->sql_query("select message from semaphores where ".
                                    "server=\"$server\" and title=\"$job\""
                                    , ";");

        #
        # Set defaults for enable/disable
        #
        $enable    = "disable";
        $enablegif = "lock.$ext";

        #
        # If the string 'build job disabled' is found change default from
        # lock to unlock.
        #
        foreach ($sqlarray as $remote) {
            if (( FALSE ==! strpos($remote,
                "$job build job disabled"))) {
                $enable    = "enable";
                $enablegif = "lock_open.$ext";
            }
        } 

        #
        # Setup array to be returned for use in the jobmenu.
        #
        $command   = array(
            
            "$enable" => array(
                "parent"  => "/adminbroker.php",
                "link"    => "?cmd=$enable&server=$server&jobname=$job".
                             "&sleep=1&access=login",
                "tooltip" => "$enable $job",
                "icon"    => "$enablegif"
            )

        );

        #
        # Return the array
        #
        return($command);

    }

    function _getrunningclass($SQL, $buildserver, $rec) {

        $running = array();
        
        if (isset($rec)) {

            $runinfo = _getRunInfo($SQL, $buildserver, $rec);

            if ((strpos($runinfo, "Overdue")) !== false) {
                $class = "overdue";
            } else {
                $class = "jobname";
            }

        }

        $running['message'] = $runinfo;
        $running['class']   = $class;
 
        return $running;

    }

    function _isie() {

        $ieString = 'MSIE';

        $browser = $_SERVER['HTTP_USER_AGENT'];

        $pos = strpos($browser, $ieString);

        return $pos;

    }
        
    function _displayactiveservers($sqlarray, $server) {

        foreach ($sqlarray as $rec) {
            $servers["$rec"] = "";
        }

        $isie = _isie();

        echo "<div id=\"header\">\n".
             "    <ul>\n";
    
        foreach ($servers as $key => $value) {
    
            if (!strcmp($server, $key) != 0) {
                echo "        <li id=\"selected\"><a href=/cabie.php?server=".
                     "$server&action=view>$server</a></li>\n";
                $buildserver = $key;
            } else {
                $url = "/cabie.php?server=$key&action=view&recs=";
                echo "        <li><a href=# onClick=\"getDisplay('$url');\">$key</a></li>\n";
                #echo "        <li><a href=/cabie.php?server=$key&action=".
                #     "view>$key</a></li>\n";
            }
        }

        echo "    </ul>\n".
             "</div>\n";
        if (!$isie) {
             echo "<div id=\"content\">\n";
        }
        echo "<table border=0 width=100%>\n".
             "<tbody>\n";


    }
    
    function _getactivejobs($SQL, $buildserver) {

        $sqlarray = $SQL->sql_query("select title from configuration where ". 
                                    "server=\"$buildserver\" and state='0'", 
                                    ";");
                                    #"server=\"$buildserver\"", 
                                    #";");
        return $sqlarray;

    }

    function _formatElapsedTime($difference) {

        $seconds    =  $difference % 60;
        $difference = ($difference - $seconds) / 60;
        $minutes    =  $difference % 60;
        $difference = ($difference - $minutes) / 60;
        $hours      =  $difference % 24;
        $difference = ($difference - $hours)   / 24;
        $days       =  $difference % 7;
        $weeks      = ($difference - $days)    /  7;

        $returnstring = sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);

        return $returnstring;

    }

    function serverport($SQL, $buildserver) {

        $sqlarray = $SQL->sql_query("select port from buildservers where ". 
                                    "server=\"$buildserver\"", ";");
        return $sqlarray[0];

    }

    function serverup($SQL, $buildserver) {

        $sqlarray = $SQL->sql_query("select status from buildservers where ". 
                                    "server=\"$buildserver\"", ";");
        return $sqlarray[0];

    }

    function utrim($source){

        $temp = ltrim($source);
        $temp = rtrim($temp);
        $temp = trim($temp);
   
        return $temp;

    }

    function displaymessage($server, $message) {
    
        echo "<tr><td class=\"jobname\" colspan=1>$server: $message</td>".
             "</tr>\n";

        echo "</tbody>\n";
        echo "</table>\n";

    }
        
    function errormessage($message, $cols) {

        echo "<tr><td class=\"jobname\" colspan=$cols>$message</td>".
                     "</tr>\n";

    }

    function processrequest($request, $cmd, $cmdclass, $cmdarray, $chained) {

        $cols    = $cmdarray['cols'];
        $title   = $cmdarray['title'];
        $header  = $cmdarray['header'];
        $footer  = $cmdarray['footer'];
        $chain   = $cmdarray['chain'];
        $pre     = $cmdarray['pre'];
        $level   = $cmdarray['level'];
        $server  = $cmdarray['server'];
        $alt     = $cmdarray['alt'];
        $jobname = $_REQUEST['jobname'];

        if ($cols) {
            if (!$chained) {
                echo "<tr><td class=\"jobname\" colspan=$cols>$title</td>".
                     "</tr>\n";
            }
            echo "$header\n";
        }
    
        $preformat    = $request['pre'];
        $remoteserver = $cmdarray['server'];
        $remoteport   = $cmdarray['port'];
    
        $args = $cmdarray['args'];
 
        if (isset($alt)) {
            $resp = _server_request($cmdarray['server'], $cmdarray['port'],
                                    $alt, "$args");
        } else {
            $resp = _server_request($cmdarray['server'], $cmdarray['port'],
                                    $cmd, "$args");
        }
    
        if ($preformat || $pre) {
            print "<pre>\n";
            foreach ($resp as $entry) {
                echo $entry;
            }
            print "</pre>\n";
        } else {
            foreach ($resp as $entry) {
                echo $entry;
            }
        }
    
        if (isset($footer)) {
            echo "$footer\n";
        }

        echo "</tbody>\n";
        echo "</table>\n";

        if (isset($chain)) {
            $chainarray = $cmdclass->_returnusercmd($chain);
            echo "<table border=0 width=100%>\n";
            echo "<tbody>\n";
            processrequest($request, $chain, $cmdclass, $chainarray, 1);
        }

        if (isset($jobname)) {

            echo "<table border=0 width=100%>\n";
            $id = $jobname."_id";
            echo "<tbody class='collapse_obj' id=$id server=$server ".
                 "jobname=$jobname length='0'>\n".
                 #"<td class=serveract colspan=8></td>\n".
                 "</tbody>\n".
                 "</table>\n";

        }


    }

    function _server_request($host, $port, $request, $args) {

        $client = new xmlrpc_client("$host:$port");
        $client->return_type = 'phpvals';
        $message = new xmlrpcmsg($request, 
                                 array(new xmlrpcval("$args", "string"))
                                );
        $resp = $client->send($message);
        if ($resp->faultCode()) {
            return $resp->faultString();
        } else {
            return $resp->value();
        }

    }

    function _getRunInfo($SQL, $server, $jobname) {

        $sqlarray = $SQL->sql_query("select keeplevel from configuration ".
                                    "where title=\"$jobname\" and server=".
                                    "\"$server\"", ";");

        $keeplevel = $sqlarray[0];

        $sqlarray = $SQL->sql_query("select start, end from jobs where ".
                                    "title=\"$jobname\" and server=".
                                    "\"$server\" and status='0' or ".
                                    "status='2' or status='3' order by job ".
                                    "desc limit $keeplevel", ";");

        $numrecs = count($sqlarray);
     
        if ($numrecs) {

            if ($numrecs < $keeplevel) {
                $keeplevel = $numrecs;
            }

            foreach ($sqlarray as $times) {
                list($start,$end) = explode(";", $times);
                $length += ($end - $start);
            }
    
            $avg = $length/$keeplevel;
    
            $avg += ($avg * .20);
    
            $average = sprintf("%d", $avg);
     
        } else {
        
            $average = 0;

        }

        $sqlarray = $SQL->sql_query("select * from semaphores where title=".
                                    "\"$jobname\" and server=\"$server\"", 
                                    ";");

        $numrecs = count($sqlarray);

        if ($numrecs) {

            foreach ($sqlarray as $record) {
    
                list($svr,$ttle,$msg,$tme,$ste) = explode(";", $record);
    
                if ((strpos($msg, "in progress")) !== false) {

                    $now = $SQL->_get_hosttime();
                    $pct = sprintf ("%d", (($now - $tme)/$average) * 100);
                    $lng = $now-$tme;

                    $lng/$average." ".$average/100;

                    $pctmsg = sprintf ("%01.2f", (($now - $tme)/$average) 
                                       * 100);

                    $update = sprintf("%d", $average/100);

                    if ($lng > $average) {
                        $over = $lng - $average;
                    }

                    if ($pct > 100) {
                        $pct = 100;
                        $msg = "Overdue ("._formatElapsedTime($over).")";
                    } else {
                        $msg = "$pctmsg% (".
                            _formatElapsedTime($average-($now-$tme)).")";
                    }

                    $grph = $pct *.50;

                    $date = date('m:d:Y h:i:s A', $tme);

                    return "<img src=\"/icons/building.gif\" width=$grph% ".
                           "height=10/>&nbsp;<a href=/userbroker.php?cmd=".
                           "buildlog&server=$svr&jobname=$ttle&buildtype=".
                           "retail>$msg</a>";
                }
    
                if ((strpos($msg, "disabled")) !== false) {
                    $date   = date('m/d/Y h:i:s A', $tme);
                    return "disabled since $date";
                }
            }
        } 

        $now = $SQL->_get_hosttime();

    }

    function _displayheader($randomimages) {

        $image = _randomimage($randomimages);

        foreach ($_COOKIE as $key => $value) {
            # _debug("$key: $value");
            $state = explode(",", $key);
        }

        $server = $_REQUEST['server'];

        echo "<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>\n".
             "<head>\n".
             "<title>cabie dashboard</title>\n".
             "<link rel='stylesheet' href='/cabie.css' type='text/css'>\n".
             "</head>\n".
             # "<body onload=\"init(); \">\n".
             "<body onload=\"init(); doLoad(); callAjax('$server');\">\n".
             "<div id='loading' style='position:absolute; width:100%; ".
             "text-align:center; top:300px;'><img src=/icons/random.images/".
             "$image border=0></div>\n".
             "<script type='text/javascript' src='javascript/wz_tooltip.js'>".
             "</script>\n".
             "<script type='text/javascript' src='javascript/collapse.js'>".
             "</script>\n".
             "<script type='text/javascript' src='javascript/cabie.js'>".
             "</script>\n";

        echo "<script>\n";
        sajax_show_javascript()."\n";
        echo "</script>\n";

    }

    function _updatequery($SQL, $tabledefs, $table, $oldvalues, $newvalues, 
                          $cond) {

        $a       = 0;
        $bChange = 0;

        $query = "update $table set ";

        $user = $_SESSION['PHP_AUTH_USER'];

        foreach ($tabledefs as $key => $value) {
            if (strcasecmp($key, "verification") != 0) {
                if (strcasecmp($oldvalues[$a], $newvalues[$a]) != 0) {
                    $level = $value['level'];
                    $ok = _verifylevel($SQL, $user, $userlevel);
                    if (!$ok) {
                        return '';
                    }
                    if (isset($value['md5'])) {
                        $newval = md5($newvalues[$a]);
                    } else {
                        $newval = $newvalues[$a];
                    }
                    $query .= "$key=\"".$newval."\", ";
                    $bChange = 1;
                }
                $a++;
            }
        }
 
        if ($bChange) {
            $query = substr("$query", 0, -2);
            $query .= " $cond";
        }
        
        if ($bChange) {
            return $query;
        } else {
            return '';
        }

    }
    
    function _genvalidate($name, $data) {
    
        foreach ($data as $key => $value) {
            $return .= "frmvalidator.addValidation(\"$name\",\"$key\",".
                       "\"$name: $value\");\n";
        }

        return $return;

    }
  
    function _genForm($SQL, $table, $tname, $data, $server, $title, $number,
                      $referer) {

        $values = explode("+", $data);
        $user   = $_SESSION['PHP_AUTH_USER'];

        $userlevel = _returnlevel($SQL, $user);

        $a = 0;
     
        echo "<tr>\n".
             "    <td class=colnames width=33%>Field Description</td>\n".
             "    <td class=colnames width=66%>Current Value</td>\n".
             "</tr>\n";

        if (isset($number)) {
            echo "<form action=/editor.php?server=$server&title=$title&jobno".
                 "=$number method=\"post\" name=\"$tname\">\n";
        } else {
            echo "<form action=/editor.php?server=$server&title=$title ".
                 "method=\"post\" name=\"$tname\">\n";
        }

        $verification = "";

        $c = 0;

        foreach ($table as $key => $value) {

            if (strcasecmp($type, "verification") != 0) {
                $tempdata   .= "$values[$a]+";
            }

            $description = $table{"$key"}{"description"};
            $type        = $table{"$key"}{"type"};
            $editable    = $table{"$key"}{"editable"};
            $size        = $table{"$key"}{"size"};
            $level       = $table{"$key"}{"level"};

            if ($userlevel < $level) {
                $editable = 0;
            }

            if (strcasecmp($type, "verification") != 0) {
                $contents = $values[$a];
            } else {
                $contents = $verification;
            }

            $viewsize = strlen($contents);

            if ($viewsize < $size) {
                if ($size > 64) {
                    $viewsize = 64;
                } else {
                    $viewsize = $size;
                }
            }

            $formatted = sprintf("$description", $title);

            echo "<tr>\n";

            switch ($type) {

                case "input":

                    $validate = $table{"$key"}{"validate"};

                    echo "    <td class=values valign=top width=33%>".
                         "$formatted:</td>\n".
                         "    <td class=values>\n";
    
                    if ($editable) {
                        echo "\t<input type=\"text\" name =\"$key\" ".
                             "maxlength=\"$size\" size=\"$viewsize\" ".
                             "value=\"$contents\">\n";
                    } else {
                        echo "\t<input type=\"text\" name =\"$key\" maxlength=".
                             "\"$size\" readonly size=\"$viewsize\" value=".
                             "\"$contents\">\n";
                    }

                    if (isset($validate)) {
                        $validation .= _genvalidate($key, $validate);
                    }

                    echo "    </td>\n";
                    echo "</tr>\n";
    
                    $a++;

                    break;

                case "password":

                    $validate = $table{"$key"}{"validate"};

                    echo "    <td class=values valign=top width=33%>".
                         "$formatted:</td>\n".
                         "    <td class=values>\n";
    
                    if ($editable) {
                        echo "\t<input type=\"password\" name =\"$key\" ".
                             "maxlength=\"$size\" size=\"$viewsize\" ".
                             "value=\"$contents\">\n";
                    } else {
                        echo "\t<input type=\"password\" name =\"$key\" ".
                             "maxlength=".
                             "\"$size\" readonly size=\"$viewsize\" value=".
                             "\"$contents\">\n";
                    }

                    if (isset($validate)) {
                        $validation .= _genvalidate($key, $validate);
                    }

                    echo "    </td>\n";
                    echo "</tr>\n";

                    $verification = $contents;
    
                    $a++;

                    break;

                case "verification":

                    $validate = $table{"$key"}{"validate"};

                    echo "    <td class=values valign=top width=33%>".
                         "$formatted:</td>\n".
                         "    <td class=values>\n";
    
                    if ($editable) {
                        echo "\t<input type=\"password\" name =\"v_$key\" ".
                             "maxlength=\"$size\" size=\"$viewsize\" ".
                             "value=\"$verification\">\n";
                    } else {
                        echo "\t<input type=\"password\" name =\"$key\" ".
                             "maxlength=".
                             "\"$size\" readonly size=\"$viewsize\" value=".
                             "\"$verification\">\n";
                    }

                    if (isset($validate)) {
                        $validation .= _genvalidate($key, $validate);
                    }

                    echo "    </td>\n";
                    echo "</tr>\n";

                    break;


                case "textarea":
                case "appendtextarea":

                    $validate = $table{"$key"}{"validate"};
                    $rows     = $table{"$key"}{"rows"};

                    echo "    <td class=values valign=top width=33%>".
                         "$formatted:</td>\n".
                         "    <td class=values>\n";
    
                    if ($editable) {
                        echo "\t<textarea name =\"$key\" rows=".
                             "\"$rows\" cols=\"$viewsize\">\n".
                             "$contents\n".
                             "\t</textarea>\n";
                    } else {
                        echo "\t<textarea name =\"$key\" rows=".
                             "\"$rows\" readonly cols=\"$viewsize\">\n".
                             "$contents\n".
                             "\t</textarea>\n";
                    }

                    if (isset($validate)) {
                        $validation .= _genvalidate($key, $validate);
                    }
    
                    echo "    </td>\n";
                    echo "</tr>\n";
    
                    $a++;
    
                    break;

                case "option":

                    $validate = $table{"$key"}{"validate"};
                    $options  = $table{"$key"}{"selection"};
                    $one      = $table{"$key"}{"bool"}{"1"};
                    $zero     = $table{"$key"}{"bool"}{"0"};

                    $len = strlen($one);

                    $set = $table{"$key"}{"bool"}{"$contents"};

                    $exists = strlen($set);

                    echo "    <td class=values valign=top width=33%>".
                         "$formatted:</td>\n".
                         "    <td class=values>\n";
    
                    if ($editable) {

                        echo "\t<select name=\"$key\">\n";

                        foreach ($options as $name => $default) {
                            if ($exists) {
                                if (_isEqual($set, $name)) {
                                    echo "\t    <option value=\"$name\" ".
                                         "selected=\"selected\">$name".
                                         "</option>\n";
                                } else {
                                    echo "\t    <option value=\"$name\">$name".
                                         "</option>\n";
                                }
                            } else {
                                if (_isEqual($name, $contents)) {
                                    echo "\t    <option value=\"$name\" ".
                                         "selected=\"selected\">$name".
                                         "</option>\n";
                                } else {
                                    echo "\t    <option value=\"$name\">$name".
                                         "</option>\n";
                                }
                            }
                        }
                        echo "\t</select>\n";
                    } else {
                        echo "\t<select name=\"$key\">\n";
                        foreach ($options as $name => $default) {
                            echo "\t    <option disabled value=\"$name\">$name".
                                 "</option>\n";
                        }
                        echo "\t</select>\n";
                    }

                    if (isset($validate)) {
                        $validation .= _genvalidate($key, $validate);
                    }
    
                    echo "    </td>\n";
                    echo "</tr>\n";

                    $a++;

                    break;

            }
        }

        echo "<tr>\n".
             "    <td class=serveract>\n".
             "\t<input type=\"hidden\" name=\"referer\" value=\"$referer\"/>\n".
             "\t<input type=\"hidden\" name=\"table\" value=\"$tname\"/>\n".
             "\t<input type=\"hidden\" name=\"temp\" value=\"$tempdata\"/>\n".
             "\t<input type=\"submit\" name=\"submit\" value=\"Submit\"/>\n".
             "\t<input type=\"reset\" name=\"task\" value=\"Reset\"/>\n".
             "    </td>\n".
             "    <td class=serveract></td>\n".
             "</tr>\n".
             "</form>\n";

        if (isset($validation)) {
             echo "<script language=\"JavaScript\" type=\"text/javascript\">\n".
                  "var frmvalidator = new Validator(\"$tname\");\n".
                  $validation.
                  "</script>\n";
        }
             

    }

    function displayusers($sql, $cmdarray) {

        $title  = $cmdarray['title'];
        $header = $cmdarray['header'];
        $class  = $cmdarray['class'];
        $cols   = $cmdarray['cols'];
        $server = $cmdarray['server'];

        $user = $_SESSION['PHP_AUTH_USER'];

        if ($cols) {
            echo "<tr><td class=\"jobname\" colspan=$cols>$title</td>".
                 "</tr>\n";
            echo "$header\n";
        }

        $sqlarray = $sql->sql_query("select username, userrealm, realmid ".
                                    "from users order by username", ";");

        $level = _returnlevel($sql, $user);

        foreach ($sqlarray as $entry) {
            $c = 0;
            $record = explode(';', $entry); 
            echo "<tr>\n";
            while ($c < count($record)) {
                if ($c === 0) {
                    if ($level < 99) {
                        if (strcmp($record[$c], $user) == 0) {
                            echo "    <td class=$class><a href=/editor.php?".
                                 "server=$server&name=$record[$c]&action=".
                                 "edit&table=users&user=1&access=login>".
                                 "$record[$c]</a></td>\n";
                        } else {    
                            echo "    <td class=$class>$record[$c]</td>\n";
                        }
                    } else {
                        echo "    <td class=$class><a href=/editor.php?server=".
                             "$server&name=$record[$c]&action=edit&table=users".
                             "&user=1&access=login>$record[$c]</a></td>\n";
                    }
                } else {
                    echo "<td class=$class>$record[$c]</td>\n";
                }
                $c++;
            }
            echo "</tr>\n";
        }

        $args = $cmdarray['args'];
    
        echo "</tbody>\n";
        echo "</table>\n";

    }

    function trace($start, $end, $message) {

        $length = $end-$start;

        _debug("$message: $length");

    }

?>
